{% extends "myhome_base.html" %}

{% load seahub_tags i18n upload_tags avatar_tags %}
{% load url from future %}

{% block extra_style %}
<style type="text/css">
    .wide-panel {
        width:600px;
        padding:10px 20px 20px;
    }
    .avatar {
        vertical-align:middle;
    }
</style>
{% endblock %}

{% block main_panel %}
<div class="wide-panel">
    <div id="upload-file-dialog">
        <h3>{% blocktrans %}Upload files to <span class="op-target">{{ dir_name }}</span>{% endblocktrans %}</h3>
        <p>{% trans "shared by:" %} {{username|email2nickname}} {% avatar username 16 %} </p>
        {% if no_quota %}
        <p class="error">{% trans "The owner of this library has run out of space." %}</p>
        {% else %}
        <form id="upload-file-form" enctype="multipart/form-data" method="post" action="">{% csrf_token %}
            <div class="row fileupload-buttonbar">
                <div>
                    <span class="fileinput-button vam" id="add-file">
                        <span class="icon-plus"></span>
                        <span>{% trans "Add Files" %}</span>
                        <input type="file" name="file" multiple />
                    </span>
                    {% if enable_upload_folder %}
                    <span class="fileinput-button vam" id="add-folder" style="display:none;">
                        <span class="icon-plus"></span>
                        <span>{% trans "Add folder" %}</span>
                        <input type="file" name="file" multiple directory webkitdirectory />
                    </span>
                    {% endif %}
                    <button type="reset" class="cancel vam">
                        <span class="icon-ban-circle"></span>
                        <span>{% trans "Cancel All" %}</span>
                    </button>
                </div>
                <ol class="tip">
                    <li>{% trans "File Drag & Drop is supported for Chrome, Safari 5.0+, Firefox 4.0+, IE 10.0+" %}</li>
                    {% if enable_upload_folder %}
                    <li>{% trans "Folder Drag & Drop is supported for Chrome" %}</li>
                    {% endif %}
                    {% if max_upload_file_size %}
                    <li>{% blocktrans with max_file_size=max_upload_file_size|filesizeformat %}File size should be smaller than {{ max_file_size }}{% endblocktrans %}</li>
                    {% endif %}
                </ol>
                <div class="fileupload-progress fade">
                    <div class="progress progress-success progres-striped active">
                        <div class="bar" style="width:0%"></div>
                    </div>
                    <div class="progress-extended"></div>
                </div>
                <p class="saving-tip alc hide"><img src="{{MEDIA_URL}}img/loading-icon.gif" alt="" style="margin-right:5px;" class="vam" />{% trans "Saving..." %}</p>
            </div>
            <table class="table table-striped"><tbody class="files" data-toggle="modal-gallery" data-target="#modal-gallery"></tbody></table>
        </form>
    {% endif %}
    </div>
</div>
{% endblock %}

{% block extra_script %}
{% if not no_quota %}
{% upload_js %}
<script type="text/javascript" src="{{ MEDIA_URL }}js/jquery.fileupload.min.js"></script>
<script type="text/javascript">
// for file upload
window.locale = { 
    "fileupload": {
        "errors": {
            "maxFileSize": "{% trans "File is too big" %}",
            "minFileSize": "{% trans "File is too small" %}",
            "acceptFileTypes": "{% trans "Filetype not allowed" %}",
            "maxNumberOfFiles": "{% trans "Max number of files exceeded" %}",
            "uploadedBytes": "{% trans "Uploaded bytes exceed file size" %}",
            "emptyResult": "{% trans "Empty file upload result" %}"
        },  
        "error": "{% trans "Error" %}",
        "uploaded": "{% trans "uploaded" %}",
        "canceled": "{% trans "canceled" %}",
        "start": "{% trans "Start" %}",
        "cancel": "{% trans "Cancel" %}",
        "destroy": "{% trans "Delete" %}"
    }   
};

var form = $('#upload-file-form');
var saving_tip = $('.saving-tip', form);

// Initialize the jQuery File Upload widget:
form.fileupload({
    formData: {'parent_dir': "{{path}}"},
    // customize it for 'done'
    getFilesFromResponse: function (data) {
        if (data.result) {
            return data.result;
        }
    },
    autoUpload: true,
    {% if max_upload_file_size %}
    maxFileSize: {{ max_upload_file_size }}, // in bytes
    {% endif %}
    maxNumberOfFiles: 500,
    sequentialUploads: true
})
.bind('fileuploadadd', function(e, data) {
    {% if enable_upload_folder %}
    // when add folder, a subdirectory will be shown as '.'. rm it.
    var file = data.files[0];
    if (file.name == '.') {
        data.files.shift();
    }
    if (file.webkitRelativePath) { // for 'upload folder'
        file.relative_path = file.webkitRelativePath;
    }
    if (file.relativePath) { // for 'folder drag & drop'
        file.relative_path = file.relativePath + file.name;
    }
    {% endif %}
})
.bind('fileuploadsubmit', function(e, data) {
    var _this = $(this);
    var file = data.files[0];
    // get url(token) for every file
    if (!file.error) {
        $.ajax({
            url: '{% url 'get_file_upload_url_ul' uploadlink.token %}?&r={{uploadlink.repo_id }}',
            cache: false,
            dataType: 'json',
            success: function(ret) {
                {% if enable_upload_folder %}
                var file_path = file.relative_path,
                    r_path;
                if (file_path) { // 'add folder'
                    r_path = file_path.substring(0, file_path.lastIndexOf('/') + 1);
                }
                var formData = form.fileupload('option', 'formData');
                formData.relative_path = r_path || '';
                form.fileupload('option', 'formData', formData);
                {% endif %}

                data.url = ret['url'];
                data.jqXHR = _this.fileupload('send', data);
            },
            error: function() {
                file.error = "{% trans "Failed to get upload url" %}";
            }
        });
        return false;
    }
})
.bind('fileuploadprogressall', function (e, data) {
    if (data.loaded > 0 && data.loaded == data.total) {
        saving_tip.show();
    }
})
.bind('fileuploaddone', function(evt, data) {
    if (data.textStatus == 'success') {
        var file = data.result[0];
        var file_path = data.files[0].relative_path;
        file.uploaded = true;
        if (file_path) {
            file.relative_path = file_path.substring(0, file_path.lastIndexOf('/') + 1) + file.name;
        }

        var uploaded_done_link = "{% url "upload_file_done" %}" + "?fn=" + e(file.name) + "&repo_id=" + e("{{repo.id}}");
        if (file_path) {
            uploaded_done_link += '&p=' + e("{{path}}" + file_path.substr(0, file_path.lastIndexOf('/') + 1));
        } else {
            uploaded_done_link += '&p=' + e("{{path}}");
        }
        $.get(uploaded_done_link);
    }
})
.bind('fileuploadcompleted fileuploadfailed', function() {
    if ($('.files .cancel', form).length == 0) {
        saving_tip.hide();
    }
});

{% if enable_upload_folder %}
if ('webkitdirectory' in $('input[type="file"]', $('#add-file'))[0]) {
    $('#add-folder').show();
    $('#add-file, #add-folder').click(function() {
        form.fileupload(
            'option',
            'fileInput',
            $('input[type="file"]', $(this))
        );
    });
}
{% endif %}

// Enable iframe cross-domain access via redirect option:
form.fileupload(
    'option',
    'redirect',
    window.location.href.replace(/\/repo\/[-a-z0-9]{36}\/.*/, '{{MEDIA_URL}}cors/result.html?%s')
);
</script>
{% endif %}
{% endblock %}
